<template>
  <div id="box">
    <h3>{{ id ? '编辑' : '创建'}}分类</h3>
    <el-form @submit.native.prevent="save" label-width="100px">
      <el-form-item label="上级分类">
        <el-select v-model="model.parent" >
          <el-option 
              v-for="item in parents" :key="item._id"
              :label="item.name"
              :value="item._id" />
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="model.name"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    name: 'Category',
    props: {
      id: {
        type: String,
      }
    },
    data() {
      return {
        model: {},
        parents: [],
      }
    },
    methods: {
      // 获取父级列表
      async getParent() {
        const res = await this.$http.get('/rest/categories');
        this.parents = res.data
      },

      //修改 、 创建列表 
      async save() {
        try {
          let res
          // 修改分类
          if (this.id) {
            res = await this.$http.put(`/rest/categories/${this.id}`, this.model);
            this.$message({
              type: 'success',
              message: "修改成功"
            })
          } else {
            // 创建分类
            res = await this.$http.post('/rest/categories', this.model);
            this.$message({
              type: 'success',
              message: "创建成功"
            })
          }
          console.log(res);
          this.$router.push('/categories/list');
        } catch(err) {
          console.log(err);
        }
      },

      // 获取详情列表（某一个） 
      async fetch() {
        try {
          const res = await this.$http.get(`/rest/categories/${this.id}`);
          this.model = res.data
        } catch(err) {
          console.log('修改列表失败');
        }
      }
    },
    created() {
      this.getParent();
      this.id && this.fetch();
    }
  }
</script>

<style scoped>

</style>